package com.inspinia.base.mq.rabbitmq.config;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * rabbitMq 配置
 * @author Veblen
 */

@Slf4j
@Component
@Configuration
@PropertySource("classpath:rabbitMq.properties")
public class RabbitMqConfig{

    private static Connection connection = null;

    /**
     * new 当前对象
     */
    public static Connection getConnection() {
        if (connection == null) {
            try {
                connection = connectionFactory().newConnection();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                log.info("rabbitmq连接超时");
            }
        }
        return connection;
    }

    /**
     * 初始化连接
     * @return
     */
    @Bean
    public static ConnectionFactory connectionFactory(){
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(RabbitConfig.HOST);
        connectionFactory.setUsername(RabbitConfig.USERNAME);
        connectionFactory.setPassword(RabbitConfig.PASSWORD);
        connectionFactory.setVirtualHost(RabbitConfig.VHOST);
        return connectionFactory;
    }

}